package com.wanyangproject.fuwuactivity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.wanyangproject.R;
import com.wanyangproject.activity.EnclosureActivity;
import com.wanyangproject.entity.QiYeFuWuXiangQingEntity;
import com.wanyangproject.entity.ShangJiaHuoDongXiangQingEntity;
import com.wanyangproject.net.util.ToastUtil;
import com.wanyangproject.utils.ContractUtils;
import com.wanyangproject.utils.WebViewUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

//企业服务详情
public class QiYeFuWuXiangQingActivity extends AppCompatActivity {

    @BindView(R.id.image_back)
    ImageView imageBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_neirong)
    TextView tvNeirong;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.relative_shenqing)
    RelativeLayout relativeShenqing;
    @BindView(R.id.webView)
    WebView webView;
    @BindView(R.id.tv_fujian_lianjie)
    TextView tvFujianLianjie;
    @BindView(R.id.relative_xiazai)
    RelativeLayout relativeXiazai;
    private WebSettings mWebSettings;
    private String content;
    private ShangJiaHuoDongXiangQingEntity shangJiaHuoDongXiangQingEntity;
    private String huodongid;
    private QiYeFuWuXiangQingEntity qiYeFuWuXiangQingEntity;
    private ProgressDialog progressDialog;
    private static Boolean isOK = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qi_ye_fu_wu_xiang_qing);
        ButterKnife.bind(this);
        if (Build.VERSION.SDK_INT >= 21) {
            View dview = getWindow().getDecorView();
            dview.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }

        mWebSettings = webView.getSettings();
        mWebSettings.setJavaScriptEnabled(true);  //允许加载javascript
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView.getSettings().setLoadWithOverviewMode(true);
        mWebSettings.setSupportZoom(false);     //允许缩放
        mWebSettings.setBuiltInZoomControls(false); //原网页基础上缩放
        mWebSettings.setUseWideViewPort(false);   //任意比例缩放
//        mWebSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
//        mWebSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小

        Intent intent = getIntent();
        huodongid = intent.getStringExtra("id");
        System.out.println(huodongid + "    列表点击进入详情接收的id");


//        企业服务详情的网络请求
        initQiYeFuWuHttp();


//        //        服务 企业服务优惠活动详情的网络请求
//        initQiYeFuWuXiangQingHttp();

        initView();
    }


    private void initView() {
        webView.setWebViewClient(new WebViewClient() {
            /**
             * 拦截 url 跳转,在里边添加点击链接跳转或者操作
             */
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                return WebViewUtils.shouldOverrideUrlLoading(view, request, QiYeFuWuXiangQingActivity.this);
            }


            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                System.out.println("66666666666666666666");
                return WebViewUtils.shouldOverrideUrlLoading(view, url, QiYeFuWuXiangQingActivity.this);

            }


            /**
             * 在开始加载网页时会回调
             */
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                System.out.println("111111111111111111");
            }

            /**
             * 加载错误的时候会回调，在其中可做错误处理，比如再请求加载一次，或者提示404的错误页面
             */
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
            }

            /**
             * 在结束加载网页时会回调
             */
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                System.out.println("chenggongchenggongchenggong");

                if(progressDialog != null){
                    progressDialog.dismiss();
                }

            }

            /**
             * 当接收到https错误时，会回调此函数，在其中可以做错误处理
             */
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
            }

            /**
             * 在每一次请求资源时，都会通过这个函数来回调
             */
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                return null;
            }


            @Override
            public void onPageCommitVisible(WebView view, String url) {
                super.onPageCommitVisible(view, url);

                if(progressDialog != null){
                    progressDialog.dismiss();
                }
            }
        });
    }


    //    企业服务详情的网络请求
    private void initQiYeFuWuHttp() {
        progressDialog = new ProgressDialog(QiYeFuWuXiangQingActivity.this);
        progressDialog.setTitle("提示");
        progressDialog.setMessage("请等待...");
        progressDialog.setCancelable(false);
        progressDialog.show();

        OkHttpUtils.post()
                .url(ContractUtils.LOGIN_URL + "fuwu/detail")
                .addHeader("token", ContractUtils.getTOKEN(QiYeFuWuXiangQingActivity.this))
                .addParams("parkId", ContractUtils.getParkId(QiYeFuWuXiangQingActivity.this))
                .addParams("id", huodongid)
                .addParams("typeId", "2")//1:物业服务，2：企业服务
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        progressDialog.dismiss();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.println(response + "          企业服务详情的网络请求");
                        ContractUtils.Code500(QiYeFuWuXiangQingActivity.this, response);
                        if (response.indexOf("200") != -1) {
                            Gson gson = new Gson();
                            qiYeFuWuXiangQingEntity = gson.fromJson(response, QiYeFuWuXiangQingEntity.class);


                            if(qiYeFuWuXiangQingEntity.getResponse().getFujian_name() != null){
                                if(qiYeFuWuXiangQingEntity.getResponse().getFujian_name().equals("")){
                                    tvFujianLianjie.setText("未命名");
                                }else{
                                    tvFujianLianjie.setText(qiYeFuWuXiangQingEntity.getResponse().getFujian_name());
                                }
                            }


                            if(qiYeFuWuXiangQingEntity.getResponse().getFujian().equals("null") || qiYeFuWuXiangQingEntity.getResponse().getFujian().equals("")){
                                relativeXiazai.setVisibility(View.GONE);
                            }else{
                                relativeXiazai.setVisibility(View.VISIBLE);
                            }


                            if (qiYeFuWuXiangQingEntity.getResponse().getTitle() == null) {

                            } else { // 标题
                                tvTitle.setText(qiYeFuWuXiangQingEntity.getResponse().getTitle());
                            }


                            if (qiYeFuWuXiangQingEntity.getResponse().getIntroduction() == null) {

                            } else { // 内容
                                tvNeirong.setText(qiYeFuWuXiangQingEntity.getResponse().getIntroduction());
                            }


                            if (qiYeFuWuXiangQingEntity.getResponse().getAdd_time() == null) {

                            } else { // 时间
//                                tvTime.setText(qiYeFuWuXiangQingEntity.getResponse().getAdd_time());
                                tvTime.setText(stampToDate(qiYeFuWuXiangQingEntity.getResponse().getAdd_time()));//时间戳转时间
                            }


                            if (qiYeFuWuXiangQingEntity.getResponse().getContent() == null) {

                            } else {
                                //    详情html
                                content = qiYeFuWuXiangQingEntity.getResponse().getContent();
                                webView.loadDataWithBaseURL("http://www.baidu.com", getNewContent(content), "text/html", "UTF-8", null);
                            }
                        }else if(response.indexOf("400") != -1){
                            progressDialog.dismiss();
                            ContractUtils.Code400(QiYeFuWuXiangQingActivity.this,response);
                        }
                    }
                });
    }



    /*
 * 将时间戳转换为时间
  */
    public String stampToDate(String s) {
        if(s == null){
            return "";
        }

        if(s.length() == 0){
            return "";
        }

        if(s.indexOf("-") != -1){
            return "";
        }
        String res;
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YY-MM-dd HH:mm:ss");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        long lt = new Long(s);
        Date date = new Date(lt * 1000);
        res = simpleDateFormat.format(date);
        return res;
    }


    //    服务 企业服务优惠活动详情的网络请求
//    tiantian
//    parkId  和 Preferences_id  (修改)
//    private void initQiYeFuWuXiangQingHttp() {
//        OkHttpUtils.post()
//                .url(ContractUtils.LOGIN_URL + "Life/preferential")
//                .addHeader("token", ContractUtils.getTOKEN(QiYeFuWuXiangQingActivity.this))
//                .addParams("parkId", ContractUtils.getParkId(QiYeFuWuXiangQingActivity.this))
//                .addParams("Preferences_id", huodongid)
//                .build()
//                .execute(new StringCallback() {
//                    @Override
//                    public void onError(Call call, Exception e, int id) {
//
//                    }
//
//                    @Override
//                    public void onResponse(String response, int id) {
//                        System.out.println(response + "      服务 企业服务优惠活动详情的网络请求");
//                        Gson gson = new Gson();
//                        shangJiaHuoDongXiangQingEntity = gson.fromJson(response, ShangJiaHuoDongXiangQingEntity.class);
//                        if (response.indexOf("200") != -1) {
//                            if (shangJiaHuoDongXiangQingEntity.getResponse().getShopPreferences().getTitle() == null) {
//
//                            } else {  //标题
//                                tvTitle.setText(shangJiaHuoDongXiangQingEntity.getResponse().getShopPreferences().getTitle());
//                            }
//
//                            if (shangJiaHuoDongXiangQingEntity.getResponse().getShopPreferences().getAdd_time() == null) {
//
//                            } else { // 时间
//                                tvTime.setText(shangJiaHuoDongXiangQingEntity.getResponse().getShopPreferences().getAdd_time());
//                            }
//
//                            if (shangJiaHuoDongXiangQingEntity.getResponse().getShopPreferences().getIntroduction() == null) {
//
//                            } else { //  内容
//                                tvNeirong.setText(shangJiaHuoDongXiangQingEntity.getResponse().getShopPreferences().getIntroduction());
//                            }
//
//                            if(shangJiaHuoDongXiangQingEntity.getResponse().getShopPreferences().getContent() == null){
//
//                            }else{
//                                //    详情html
//                                content = shangJiaHuoDongXiangQingEntity.getResponse().getShopPreferences().getContent();
//                                webView.loadDataWithBaseURL("http://www.baidu.com", getNewContent(content),"text/html", "UTF-8", null);
//                            }
//                        }
//                    }
//                });
//    }


    /**
     * 将html文本内容中包含img标签的图片，宽度变为屏幕宽度，高度根据宽度比例自适应
     **/
    public static String getNewContent(String htmltext) {

//        if(isOK == false){
//            return htmltext;
//        }
//
//        isOK = true;
        try {
            Document doc = Jsoup.parse(htmltext);
            Elements elements = doc.getElementsByTag("img");
            for (Element element : elements) {
                element.attr("width", "100%").attr("height", "auto");
            }
            return doc.toString();
        } catch (Exception e) {
            return htmltext;
        }
    }


    @OnClick({R.id.tv_time, R.id.tv_fujian_lianjie, R.id.relative_shenqing, R.id.image_back, R.id.tv_title, R.id.tv_neirong,})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.image_back:
                finish();
                break;
//            附件链接
            case R.id.tv_fujian_lianjie:
                String fujian = qiYeFuWuXiangQingEntity.getResponse().getFujian();
                if (fujian.equals("null")) {
//                    ToastUtil.show(QiYeFuWuXiangQingActivity.this, "附件地址不存在");
                    return;
                } else {
                    EnclosureActivity.start(QiYeFuWuXiangQingActivity.this, fujian);
                }

//                Intent intent = new Intent(QiYeFuWuXiangQingActivity.this,FuJianLianJieActivity.class);
//                intent.putExtra("lianjie",qiYeFuWuXiangQingEntity.getResponse().getFujian());
//                startActivity(intent);
                break;
//            时间
            case R.id.tv_time:
                break;
//            立即申请
            case R.id.relative_shenqing:
//                typeId: 0 游客 1 普通员工 2企业用户 3商家 4 门卫 5 物业
                if (ContractUtils.getTypeId(QiYeFuWuXiangQingActivity.this).equals("2") || ContractUtils.getTypeId22(QiYeFuWuXiangQingActivity.this).equals("2")) {
                    Intent intent1 = new Intent(QiYeFuWuXiangQingActivity.this, QiYeFuWuLiJiShenQingActivity.class);
                    intent1.putExtra("id", huodongid);
                    intent1.putExtra("title", qiYeFuWuXiangQingEntity.getResponse().getTitle());
                    intent1.putExtra("jianjie", qiYeFuWuXiangQingEntity.getResponse().getIntroduction());
//                System.out.println(shangJiaHuoDongXiangQingEntity.getResponse().getShopPreferences().getTitle()+"    跳转申请传送的标题");
//                System.out.println(shangJiaHuoDongXiangQingEntity.getResponse().getShopPreferences().getIntroduction()+"    跳转申请传送的简介");
//                System.out.println(shangJiaHuoDongXiangQingEntity.getResponse().getShopPreferences().getId()+"          跳转企业申请传活动id");
                    startActivity(intent1);
                } else {
                    Toast.makeText(this, "您当前不是企业用户！", Toast.LENGTH_SHORT).show();
                }

                break;
            case R.id.tv_title:
                break;
            case R.id.tv_neirong:
                break;
        }
    }
}
